package eu.boss.activities;

import java.util.ArrayList;
import java.util.regex.Pattern;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import eu.boss.R;
import eu.boss.controller.ShadowStatsController;
import eu.boss.exceptions.AlreadyExistsException;
import eu.boss.exceptions.ServerErrorException;
import eu.boss.http.Http;

public class SignUpActivity extends Activity {
        private EditText etLogin;
        private EditText etPassword;
        private EditText etMail;
        private EditText etRetyped;
        private String mLogin;
        private String mPassword;
        private String mEmail;
        private ShadowStatsController mController;
        
        private ServiceConnection mControllerConnection = new ServiceConnection() {
                // Called when the connection with the service is established
                public void onServiceConnected(ComponentName className, IBinder service) {
                        mController = ((ShadowStatsController.LocalBinder) service).getService();
                }

                // Called when the connection with the service disconnects unexpectedly
                public void onServiceDisconnected(ComponentName className) {
                        mController = null;
                }
        };

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.signup);
                initComponents();
        }

        public void initComponents() {
                etLogin = (EditText) findViewById(R.id.etLoginLogin);
                etPassword = (EditText) findViewById(R.id.etPasswordLogin);
                etMail=(EditText) findViewById(R.id.etMail);
                etRetyped=(EditText) findViewById(R.id.etRetypedPasswordLogin);
                
                Button btn = (Button) findViewById(R.id.btnConfirmLogin);
                btn.setOnClickListener(new OnClickListener() {

                        public void onClick(View v) {
                                if ((etLogin.getText().toString().compareTo("")!=0)&&(etPassword.getText().toString().compareTo("")!=0)&&(etMail.getText().toString().compareTo("")!=0)&&(etRetyped.getText().toString().compareTo("")!=0)){
                                        if (etPassword.getText().toString().compareTo(etRetyped.getText().toString())==0){
                                                if (Pattern.matches("^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)+$", etMail.getText().toString()))
                                                {
                                                        if (etPassword.getText().toString().length()>=5){
                                                                mLogin=etLogin.getText().toString();
                                                                mPassword=etPassword.getText().toString();
                                                                mEmail=etMail.getText().toString();
                                                                new UserLoginTask().execute();
                                                        }
                                                        else
                                                                displayErrorMessage(getString(R.string.small_password));
                                                }
                                                else
                                                        displayErrorMessage(getString(R.string.invalid_mail));
                                        }
                                        else
                                                displayErrorMessage(getString(R.string.retyped_error));
                                }
                                else
                                        displayErrorMessage(getString(R.string.empty_field));
                        }
                });
        }

        @Override
        public void onStart() {
                super.onStart();
                // new intent to bind service
                Intent intent = new Intent(this, ShadowStatsController.class);
                this.bindService(intent, mControllerConnection,
                                Context.BIND_AUTO_CREATE);
        }

        @Override
        public void onDestroy() {
                super.onDestroy();
                unbindService(mControllerConnection);
        }

        
        /**
         * AsyncTask making HTTP Put request in a second thread. Updating server
         * data
         * 
         * @author Arnaud
         * 
         */
        private class UserLoginTask extends AsyncTask<Void, Void, String> {

                String error = null;
                private ProgressDialog dialog;
                
                @Override
                protected void onPreExecute(){
                        super.onPreExecute();
                        dialog= ProgressDialog.show(SignUpActivity.this, "", getString(R.string.loading));
                }
                
                @Override
                protected String doInBackground(Void... params) {

                        String url = getString(R.string.web_app_url) + getString(R.string.subscribe_url);
                        String response = null;
                        Http request = new Http();

                        try {
                                // Creation of a pair Key/Value to put on the server and get
                                // response.
                                ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
                                pairs.add(new BasicNameValuePair("email", mEmail));
                                pairs.add(new BasicNameValuePair("login", mLogin));
                                pairs.add(new BasicNameValuePair("hash", "" + (mLogin + mPassword).hashCode()));
                                response = request.executePostRequest(url, pairs, mLogin);
                                if (response.compareTo("ALREADY EXISTS")==0)
                                        throw new AlreadyExistsException(SignUpActivity.this);
                                else if (response.compareTo("SUCCESS")!=0)
                                        throw new ServerErrorException();
                                
                        } catch (Exception e) {
                                error=e.getMessage();
                        } 

                        return response;
                }

                @Override
                protected void onPostExecute(String result) {
                        super.onPostExecute(result);
                        dialog.dismiss();
                        if (error == null) {
                                //saving login in prefs
                                SharedPreferences sharedPreferences = getSharedPreferences("prefs", MODE_PRIVATE);
                                SharedPreferences.Editor editor = sharedPreferences.edit();
                                String hash=""+(mLogin + mPassword).hashCode();
                                editor.putString("hash", hash);
                                editor.commit();
                                
                                mController.setHash(hash);
                                mController.setStatsMessage(null);
                                finish();
                                startActivity(new Intent(SignUpActivity.this, FragmentsSliderActivity.class));
                        } else {
                                displayErrorMessage(error);
                        }
                };

        }

        
        /**
         * Displaying error message in an AlertDialog and exit activity
         * 
         * @param msg message to display
         */
        public void displayErrorMessage(String msg) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(getString(R.string.error));
                builder.setMessage(msg);
                builder.setPositiveButton(R.string.ok, null);
                builder.show();
        }
}